package info.demo.filter;

import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

public class Crypto {

    public static final String INIT_PARAMETER = "crypto.urlParamName";
    public static final String URL_PARAM_NAME = "_in";

    private static final String KEY = "[@B;/\u00e1`\u00aa@#%\u00a77m.|?k}5!s~*";

    private static final String CIPHER_TRANS = "DESede/ECB/PKCS5Padding";
    private static final String KEYGEN_TRANS = "DESede";

    private Crypto() {
    }

    public static SecretKey generateKey() {
        try {
            KeyGenerator keygen = KeyGenerator.getInstance(KEYGEN_TRANS);
            return keygen.generateKey();
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Invalid algorithm " + KEYGEN_TRANS, e);
        }
    }

    public static String encrypt(SecretKey key, String message) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_TRANS);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] decodedBytes = message.getBytes();
            byte[] encodedBytes = cipher.doFinal(decodedBytes);
            return HexConverter.encode(encodedBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Invalid algorithm " + CIPHER_TRANS, e);
        } catch (BadPaddingException e) {
            throw new CryptoException("Error while encrypting input message", e);
        } catch (IllegalBlockSizeException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException e) {
            throw new IllegalStateException(e);
        } catch (NoSuchPaddingException e) {
            throw new IllegalStateException("Invalid padding in " + CIPHER_TRANS, e);
        }
    }

    public static String decrypt(SecretKey key, String encryptedMessage) {
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_TRANS);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encodedBytes = HexConverter.decode(encryptedMessage);
            byte[] decodedBytes = cipher.doFinal(encodedBytes);
            return new String(decodedBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Invalid algorithm " + CIPHER_TRANS, e);
        } catch (BadPaddingException e) {
            throw new CryptoException("Error while decrypting encoded message", e);
        } catch (IllegalBlockSizeException e) {
            throw new IllegalStateException(e);
        } catch (InvalidKeyException e) {
            throw new IllegalStateException(e);
        } catch (NoSuchPaddingException e) {
            throw new IllegalStateException("Invalid padding in " + CIPHER_TRANS, e);
        }
    }

    public static String encrypt(String message) {
        return encrypt(getSecretKey(), message);
    }
    
    public static String decrypt(String encryptedMessage) {
        return decrypt(getSecretKey(), encryptedMessage);
    }

    private static SecretKey getSecretKey() {
        try {
            byte[] bytes = KEY.getBytes(Charset.forName("UTF-8"));
            DESedeKeySpec keySpec = new DESedeKeySpec(bytes);
            SecretKeyFactory skf = SecretKeyFactory.getInstance(KEYGEN_TRANS);
            return skf.generateSecret(keySpec);
        } catch (InvalidKeyException e) {
            throw new IllegalStateException("The length of the key must be 24 bytes", e);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("Invalid algorithm " + KEYGEN_TRANS, e);
        } catch (InvalidKeySpecException e) {
            throw new IllegalStateException("Invalid key specification for " + KEYGEN_TRANS, e);
        }
    }

    public static String encryptUrl(String paramName, String url) {
        if (paramName == null)
            paramName = URL_PARAM_NAME;
        if (url == null)
            return null;
        StringBuilder urlBuilder = new StringBuilder();
        int intPos;
        if ((intPos = url.indexOf("?")) == -1)
            return url;
        urlBuilder.append(url.substring(0, intPos));
        String urlQuery = url.substring(++intPos);
        if (urlQuery.length() > 0)
            urlBuilder.append("?").append(paramName).append("=").append(Crypto.encrypt(urlQuery));
        return urlBuilder.toString();
    }

    public String generateHash(String value) {
        if (value == null)
            return null;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            BigInteger bigInt = new BigInteger(1, md.digest(value.getBytes(Charset.forName("UTF-8"))));
            return bigInt.toString(16);
        } catch (NoSuchAlgorithmException e) {
            // SHA-256 is a valid algorithm
        }
        return null;
    }

}
